// https://www.lintcode.com/problem/partition-list/

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: The first node of linked list
     * @param x: An integer
     * @return: A ListNode
     */
    public ListNode partition(ListNode head, int x) {
        // write your code here
        ListNode x_head = null, x_tail = null;
        ListNode y_head = null, y_tail = null;
        while (head != null) {
            if (head.val < x) {
                if (null == x_head) {
                    x_head = head;
                    x_tail = head;
                }
                else {
                    x_tail.next = head;
                    x_tail = x_tail.next;
                }
                head = head.next;
                x_tail.next = null;
            }
            else {
                if (null == y_head) {
                    y_head = head;
                    y_tail = head;
                }
                else {
                    y_tail.next = head;
                    y_tail = y_tail.next;
                }
                head = head.next;
                y_tail.next = null;
            }
        }
        if ((null == x_head) && (null == y_head)) {
            return null;
        }
        else if (null == x_head) {
            return y_head;
        }
        else if (null == y_head) {
            return x_head;
        }
        else {
            x_tail.next = y_head;
            return x_head;
        }
    }
}